package com.mineplatform.service;

import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mineplatform.dao.M_ConsultationDao;
import com.mineplatform.dao.M_UserDao;
import com.mineplatform.domain.M_Consultation;
import com.mineplatform.domain.M_User;
import com.mineplatform.exception.FromUserNotExistException;
import com.mineplatform.exception.PriceNullOrEmptyException;
import com.mineplatform.exception.ToUserNotExistException;
import com.mineplatform.iservice.IM_ConsultationService;

@Service
public class M_ConsultationService implements IM_ConsultationService {

	private final M_UserDao _m_userdao;
	private final M_ConsultationDao _m_consultationdao;

	@Autowired
	public M_ConsultationService(M_UserDao m_userdao, M_ConsultationDao m_consultationdao) {
		this._m_userdao = m_userdao;
		this._m_consultationdao = m_consultationdao;
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void updateconsultation(String from, String to, Integer price)
			throws FromUserNotExistException, ToUserNotExistException, PriceNullOrEmptyException {
		// TODO Auto-generated method stub
		M_User fromUser = this._m_userdao.findById(from);
		if (fromUser == null) {

			throw new FromUserNotExistException();
		}
		M_User toUser = this._m_userdao.findById(to);
		if (toUser == null) {

			throw new ToUserNotExistException();
		}
		if (price == null) {

			throw new PriceNullOrEmptyException();
		}

		M_Consultation model = this._m_consultationdao.findByFromTo(from, to);

		if (model == null) {
			// add
			M_Consultation newModel = new M_Consultation();
			newModel.setId(UUID.randomUUID().toString());
			newModel.setFrom(from);
			newModel.setTo(to);
			newModel.setPrice(price);
			newModel.setLastUpdateTime(new Date());
			this._m_consultationdao.save(newModel);

		} else {
			// update
			model.setFrom(from);
			model.setTo(to);
			model.setPrice(price);
			model.setLastUpdateTime(new Date());

			this._m_consultationdao.update(model);
		}

	}

}
